package top.kaoshanji.p1ch01a;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.*;

/**
 * 使用模块消除样板式代码
 * @author kaoshanji
 * ^_^
 * create time 2025/4/22 10:53
 */
public class TemplateJDBC {

    private String sql = "select id, first_name, last_name, salary form employee where id = ?";

    /**
     * 代码清单-p1ch01a-16页a：许多Java API，例如JDBC，会涉及编写大量的样板式代码
     * @param id 主键
     * @return Employee
     */
    public Employee getEmployeeByIdV1(long id) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            conn = DriverManager.getConnection("url", "username", "password");
            stmt = conn.prepareStatement(sql);
            stmt.setLong(1, id);

            rs = stmt.executeQuery();
            Employee employee = null;
            if (rs.next()) {
                employee = new Employee();
                employee.setId(rs.getLong("id"));
                employee.setFirstName(rs.getString("first_name"));
                employee.setLastName(rs.getString("last_name"));
                employee.setSalary(rs.getBigDecimal("salary"));
            }

            return employee;

        } catch (SQLException e) {
            /// ////////
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    /// ////////
                }
            }

            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    ///  ////////
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    ///  ////////
                }
            }
        }

        return null;
    }

    /**
     * 代码清单-p1ch01a-17页a：模板能够让你的代码关注于自身的职责
     * @param id 主键
     * @return Employee
     */
    public Employee getEmployeeByIdV2(long id) {
        JdbcTemplate jdbcTemplate = null;

        return jdbcTemplate.queryForObject(sql, new RowMapper<Employee>() {
            @Override
            public Employee mapRow(ResultSet rs, int i) throws SQLException {
                Employee employee = new Employee();
                employee.setId(rs.getLong("id"));
                employee.setFirstName(rs.getString("first_name"));
                employee.setLastName(rs.getString("last_name"));
                employee.setSalary(rs.getBigDecimal("salary"));
                return employee;
            }

        }, id);

    }


}
